import React, { useEffect, useState } from 'react';
import { Modal, Form, Input, Select, message, Button, Empty } from 'antd';
import ResMethod from '../utils/ResMethod';

interface CorpusData {
  id: number;
  question: string;
  answer: string;
  status: number;
  from_model: string;
  from_class: string;
  create_time: string;
}

const CorpusList: React.FC = () => {

  const [messageApi, contextHolder] = message.useMessage();

  const [id, setId] = useState(0);
  const [question, setQuestion] = useState('');
  const [answer, setAnswer] = useState('');
  const [status, setStatus] = useState(0);
  const [from_model, setFrom_model] = useState('');
  const [from_class, setFrom_class] = useState('');
  const [create_time, setCreate_time] = useState('');

  const Suinfo = () => {
      
    messageApi.info({
      type:"success",
      content:'操作成功'
    });
  };

  const Errinfo = () => {
    
    messageApi.info({
      type:"error",
      content:'操作失败'
    });
  }

  const [haveData, SetHaveData] = useState(false);
  const getCorpusList = async () => {
    const res = await ResMethod('/corpus', 'GET')
    if (res) {
      if (res === 401){
        messageApi.info({
          type: 'error',
          content: '登录过期，请重新登录'
        });
  
        setTimeout(()=> {
          window.location.href = '/login';
        }, 400)
        
      } else {
        setCorpusData(res)
        SetHaveData(true)
      }
      
    } else {
      SetHaveData(false)
      return false
    }
  }

  const filterCorpusList = async() => {

      const postData = {
        id: id,
        question: question,
        answer: answer,
        status: status,
        from_model: from_model,
        from_class: from_class,
      }

      const res = await ResMethod('/corpus', 'GET', postData)

      if (res) {
        setCorpusData(res)
        Suinfo()
      } else {
        Errinfo()
      }
  }

  useEffect(() => {
    getCorpusList()
  }, [])


  const [corpusData, setCorpusData] = useState<CorpusData[]>([
  ]);
  const [modalState, setModalState] = useState<{
    visible: boolean;
    mode: 'create' | 'edit';
    data?: CorpusData | null;
  }>({
    visible: false,
    mode: 'create',
    data: null
  });
  const [form] = Form.useForm();

  const handleCorpusAction = (corpus: any) => {
    form.setFieldsValue(corpus);
    setModalState({
      visible: true,
      mode: 'edit',
      data: corpus
    });
  };

  const handleCorpusAdd = async () => {
    setModalState({
      visible: true,
      mode: 'create',
      data: null
    });

    
  }

  const handleAddOrEdit = async () => {

    const values = form.getFieldsValue();
    const data = await ResMethod('/corpus', 'POST', values);

    if (data) {
      Suinfo();
      getCorpusList();
      form.resetFields();
      handleCancel()
    } else {
      Errinfo();
    }
    
  };

  const handleUpdate = async () => {
    const values = form.getFieldsValue();
    const data = await ResMethod('/corpus', 'PUT', values);

    if (data) {
      Suinfo();
      getCorpusList();
      form.resetFields();
      handleCancel()
    } else {
      Errinfo();
    }
  };

  const handleDelete = async () => {
    const values = form.getFieldsValue().id;
    const data = await ResMethod(`/corpus/${values}`, 'DELETE');

    if (data) {
      Suinfo();
      getCorpusList();
      form.resetFields();
      handleCancel()
    } else {
      Errinfo();
    }
  };

  

  const handleCancel = () => {
    setModalState({
      visible: false,
      mode: 'create',
      data: null
    });

    form.resetFields();
  };

  return (
    <div className="p-8 min-h-screen w-full">
      {contextHolder}
      <div className="my-3 flex items-center">

        <span className='mx-3 font-normal text-md'>编号</span>
        <Input placeholder="请输入编号" value={id} style={{width: 80}} ></Input>

        <span className='mx-3 font-normal text-md'>问题</span>
        <Input placeholder="请输入问题" value={question} style={{width: 160}} ></Input>

        <span className='mx-3 font-normal text-md'>回答</span>
        <Input placeholder="请输入问题" value={answer} style={{width: 160}} ></Input>

        <span className='mx-3 font-normal text-md'>状态</span>
        <Select value={status}
          onChange={e => setStatus(e)}
        >
              <Select.Option value={1}>启用</Select.Option>
              <Select.Option value={0}>停用</Select.Option>
        </Select>

        <span className='mx-3 font-normal text-md'>模型</span>
        <Select value={from_model}
          onChange={e => setFrom_model(e)}
          style={{width: 120}}
        >
              <Select.Option value="通义千问">通义千问</Select.Option>
              <Select.Option value="DeepSeek-r1">DeepSeek-r1</Select.Option>
        </Select>

        <span className='mx-3 font-normal text-md'>类型</span>
        <Input placeholder="请输入回答" value={from_class} style={{width: 120}} ></Input>

        <Button type="primary" onClick={filterCorpusList} className="mx-3">
          查询
        </Button>

        <Button onClick={handleCorpusAdd}>
            新增
        </Button>


      </div>
      <div className="w-full flex flex-wrap">
        {haveData ? corpusData.map((corpus) => (
          <div
            key={corpus.id}
            onClick={() => handleCorpusAction(corpus)}
            className="m-5 flex-1/3 relative bg-white rounded-xl shadow-sm hover:shadow-md transition-all duration-300 overflow-hidden border border-gray-100"
          >
            <div className="p-6">
              <div className="flex justify-between items-start mb-4">
                <span className="text-sm font-medium text-gray-500">#{corpus.id}</span>
                <span className={`px-2 py-1 rounded-full text-xs font-medium ${
                  corpus.status ? 'bg-green-50 text-green-600' : 'bg-yellow-50 text-yellow-600'
                }`}>
                  {corpus.status ? "已启用" : "已停用"}
                </span>
              </div>
              <div className="mb-4">
                <div className="space-y-2">
                  <p className="text-sm font-medium text-gray-700">Q: {corpus.question}</p>
                  <p className="text-sm text-gray-600 line-clamp-2">A: {corpus.answer}</p>
                </div>
              </div>
              <div className="flex flex-col space-y-2">
                <div className="flex justify-between items-center text-sm">
                  <span className="text-gray-400">所属模型</span>
                  <span className="font-medium text-gray-700">{corpus.from_model}</span>
                </div>
                <div className="flex justify-between items-center text-sm">
                  <span className="text-gray-400">分类</span>
                  <span className="font-medium text-gray-700">{corpus.from_class}</span>
                </div>
                <div className="flex justify-between items-center text-sm">
                  <span className="text-gray-400">创建时间</span>
                  <span className="font-medium text-gray-700">
                    {new Date(corpus.create_time).toLocaleDateString()}
                  </span>
                </div>
              </div>
              <div className="absolute top-2 right-2 space-x-2">
              </div>
            </div>
          </div>
        )) : <div className='w-full mt-30'><Empty image={Empty.PRESENTED_IMAGE_SIMPLE} className='w-full' /></div>}
      </div>

      <Modal
        title={modalState.mode === 'edit' ? '编辑语料' : '添加语料'}
        open={modalState.visible}
        onOk={modalState.mode === "create" ? handleAddOrEdit : handleUpdate}
        onCancel={handleCancel}
      >
        <Form
          form={form}
          layout="vertical"
        >
          {modalState.mode === "edit" ? <Form.Item
            name="id"
            label="编号"
            rules={[{ required: true, message: '编号不能为空' }]}
          >
            <Input disabled />
          </Form.Item> : null}
          <Form.Item
            name="question"
            label="问题"
            rules={[{ required: true, message: '请输入问题' }]}
          >
            <Input.TextArea rows={3} />
          </Form.Item>
          <Form.Item
            name="answer"
            label="答案"
            rules={[{ required: true, message: '请输入答案' }]}
          >
            <Input.TextArea rows={4} />
          </Form.Item>
          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请输入答案' }]}
          >
            <Select>
              <Select.Option value={1}>启用</Select.Option>
              <Select.Option value={0}>停用</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="from_model"
            label="所属模型"
            rules={[{ required: true, message: '请选择模型' }]}
          >
            <Select>
              <Select.Option value="1">通义千问</Select.Option>
              <Select.Option value="2">DeepSeek</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="from_class"
            label="分类"
            rules={[{ required: true, message: '请选择分类' }]}
          >
            <Select>
              <Select.Option value="对话">对话</Select.Option>
              <Select.Option value="情感分析">情感分析</Select.Option>
              <Select.Option value="问答">问答</Select.Option>
            </Select>
          </Form.Item>
          
          {modalState.mode === "edit" ? <Form.Item
            name="create_time"
            label="创建时间"
            rules={[{ required: true, message: '创建时间不能为空' }]}
          >
            <Input disabled />
            </Form.Item> : null}
            <Button onClick={handleDelete}>
            删除
        </Button>
        </Form>
      </Modal>
    </div>
  );
};

export default CorpusList;